package com.lightsaber.trade.core.service.account.impl;

import java.util.LinkedHashMap;
import java.util.List;

import org.apache.commons.lang.xwork.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.lightsaber.trade.core.dao.account.AuthorityDao;
import com.lightsaber.trade.core.entity.account.Authority;
import com.lightsaber.trade.core.service.account.AuthorityService;

/**
 * @author LiuJian
 * @version 1.0
 * @created 20-11-2009 18:09:35
 */

@Service
@Transactional
public class AuthorityServiceImpl implements AuthorityService {
    final static Logger LOG = LoggerFactory.getLogger(AuthorityServiceImpl.class);

    @Autowired
    AuthorityDao authorityDao;

    /**
     * @author LiuJian
     * @return 在 Authority表中, 抽出带Intercept URL的 记录
     */
    public List<Authority> getUrlResourceWithAuthorities() {

        return authorityDao.getAuthorityWithInterceptUrl();

    }

    public LinkedHashMap<String, String> getRequestMap() throws Exception {

        List<Authority> authorityList = getUrlResourceWithAuthorities();

        LinkedHashMap<String, String> requestMap = new LinkedHashMap<String, String>(
                authorityList.size());

        for (Authority authority : authorityList) {
            String authorities = requestMap.get(authority.getInterceptUrl());

            if (StringUtils.isBlank(authorities)) {
                authorities = authority.getName();
            } else {
                authorities = authorities + "," + authority.getName();
            }

            requestMap.put(authority.getInterceptUrl(), authorities);
        }

        for (String interceptor : requestMap.keySet()) {
            LOG.info("Spring-Security URL interceport: URL={}, Authoryties={}", interceptor,
                    requestMap.get(interceptor));
        }

        return requestMap;
    }

    @Override
    public List<Authority> findByUserAndRole(String userName, String roleCode) {
        return authorityDao.findByUserAndRole(userName, roleCode);
    }
}